//
//  NetworkHandlerBlock.m
//  喜马拉雅FM
//
//  Created by dllo on 16/1/26.
//  Copyright © 2016年 lanou.com. All rights reserved.
//

#import "NetworkHandlerBlock.h"
#import "AFNetworking.h"

#import <MBProgressHUD.h>
#import <CommonCrypto/CommonDigest.h>

#import "Reachability.h"


@implementation NetworkHandlerBlock

+ (void)netWorkingWithURL:(NSString *)string completeHandle:(void (^)(NSURLResponse *, NSData *, id))block {

    //字符串转码
    NSString *codeString = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    //网址对象
    NSURL *url = [NSURL URLWithString:codeString];
    
    //session
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url
                                            completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        dispatch_async(dispatch_get_main_queue(), ^{
            if (data)
            {
                NSString *defaut = @"default/com.hackemist.SDWebImageCache.default/";
                NSString *behind = @".data";
                // 获取沙盒中Document的路径.
                NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                
                NSString* path =[libPath stringByAppendingPathComponent:[defaut stringByAppendingFormat:@"%@%@",[NetworkHandlerBlock md5HexDigest:string],behind]];
           
                [data writeToFile:path  atomically:YES];
                
                // 数据解析
                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                
                // 调用 block
                block(response,data ,result);
            }
            else
            {
                
                
                NSString *defaut = @"default/com.hackemist.SDWebImageCache.default/";
                
                NSString *behind = @".data";
                
                NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                
                NSString* path =[libPath stringByAppendingPathComponent:[defaut stringByAppendingFormat:@"%@%@",[NetworkHandlerBlock md5HexDigest:string],behind]];
                
                NSMutableData *data1 = [NSMutableData dataWithContentsOfFile:path];
                
                if (data1 == nil)
                {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"InternetIsNo" object:nil];
                    
                    return;
                    
                } else
                {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"InternetIsNo" object:nil];
                    
                    id result = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];
                    
                    block(nil, nil, result);
                }
                
            }
        });
    }];
    [dataTask resume];
}




+ (NSString *)md5HexDigest:(NSString*)input
{
    const char* str = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
//    CC_MD5(<#const void *data#>, <#CC_LONG len#>, <#unsigned char *md#>)
    CC_MD5(str, (unsigned int)strlen(str), result);
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
    {
        [hash appendFormat:@"%02X", result[i]];
    }
    NSString *mdfiveString = [hash lowercaseString];
    
    return mdfiveString;
}






#if 0
{
    // App包路径.
    NSString *appPath = [[NSBundle mainBundle]resourcePath];
    
    // 沙盒路径.
    NSString *sandBoxPath = NSHomeDirectory();
    
    // 资源库路径.
    NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)lastObject];
    
    // 缓存路径.
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    
    // 获取Preferences文件夹路径.(拼接)
    NSString *prePath1 = [libraryPath stringByAppendingString:@"/Preferences"];
    
    // 常用这种方法拼接字符串得到想要的路径.此方法可以省略斜杠.
    NSString *prePath = [libraryPath stringByAppendingPathComponent:@"/Preferences"];
    NSLog(@"%@",prePath);
}
#endif







@end
